package com.jiangxiaofei.citycloud.activity.fleamarket;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.EmptyUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.VillagePublishHeaderPhotoAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.GoodIdBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.IntConstants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.FleaConstant;
import com.jiangxiaofei.citycloud.mvp.FleaPersenter;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.param.GoodsPublicParam;
import com.jiangxiaofei.citycloud.param.UpLoadPhotoParam;
import com.jiangxiaofei.citycloud.util.PickerImageLoader;
import com.jiangxiaofei.citycloud.view.SlidingRecyclerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author: JiangXfei
 * @date: 2017/10/30 0030
 * @title:物品发布
 */

public class FleaMarketHavePublishActivity extends BaseActivity implements FleaConstant.PutFleaGoodsView, MainConstant.UpLoadPhotoView {
    public static final int SHOWADDPHOTO = 0x0001;
    public static final int HIDEADDPHOTO = 0x0002;
    private static final int IMAGE_PICKER = 0X0003;
    public static final int TYPERESULT = 0X0004;

    @InjectView(R.id.img_add_photo)
    ImageView imgAddPhoto;
    @InjectView(R.id.tv_add_photo)
    TextView tvAddPhoto;
    @InjectView(R.id.img_add_photo_litter)
    ImageView imgAddPhotoLitter;
    @InjectView(R.id.recy_photo_list)
    SlidingRecyclerView recyPhotoList;
    @InjectView(R.id.hsv_photo_list)
    HorizontalScrollView hsvPhotoList;
    @InjectView(R.id.et_flea_title)
    EditText etFleaTitle;
    @InjectView(R.id.et_flea_content)
    EditText etFleaContent;
    @InjectView(R.id.linear_select_type)
    LinearLayout linearSelectType;
    @InjectView(R.id.linear_select_price)
    LinearLayout linearSelectPrice;
    @InjectView(R.id.btn_publish)
    Button btnPublish;
    @InjectView(R.id.tv_good_type)
    TextView tvGoodType;
    @InjectView(R.id.tv_good_price)
    EditText tvGoodPrice;


    List<String> imgList = new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOWADDPHOTO:
                    //显示添加图片
                    hsvPhotoList.setVisibility(View.GONE);
                    tvAddPhoto.setVisibility(View.VISIBLE);
                    break;
                case HIDEADDPHOTO:
                    hsvPhotoList.setVisibility(View.VISIBLE);
                    tvAddPhoto.setVisibility(View.GONE);
                    int position = (int) msg.obj;
                    imgList.remove(position);
                    //隐藏添加图片
                    break;
                default:
                    break;
            }
        }
    };

    private VillagePublishHeaderPhotoAdapter photoAdapter;
    private ArrayList<ImageItem> images = new ArrayList<>();
    private GoodsPublicParam goodParam;

    private FleaConstant.PutFleaGoodsPersenter putFleaGoodsPersenter;
    private int id = -1;
    private PopupWindow popupWindowPublishSuccess;
    private Button btnClose;
    private UpLoadPhotoParam param;
    private MainConstant.UploadPhotoPersenter uploadPhotoPersenter;
    private int goodsId = 0;
    private BDLocation bdLocation;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_flea_marker_publish_layout);
        ButterKnife.inject(this);
        mActivity = this;
        mContext = this;
        initTitle();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        recyPhotoList.setLayoutManager(linearLayoutManager);
        initPicker();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);//设置软件盘默认不弹出
        goodParam = new GoodsPublicParam();
        putFleaGoodsPersenter = new FleaPersenter(mContext, (FleaConstant.PutFleaGoodsView) mActivity);
        initPopupSuccess();
        uploadPhotoPersenter = new MainPersenter(mContext, (MainConstant.UpLoadPhotoView) mActivity);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        setLeftOneBg(R.drawable.ic_back_black);
        setCTitle("发布宝贝");
        mCenterTitle.setTextColor(Color.parseColor("#7b7b7b"));
        rl_layout.setBackgroundColor(Color.parseColor("#ffffff"));
    }

    /**
     * 初始化图片裁剪器
     */
    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickerImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    /**
     * 点击事件
     */
    @OnClick({R.id.img_add_photo, R.id.tv_add_photo, R.id.img_add_photo_litter,
            R.id.linear_select_type, R.id.btn_publish})
    public void bOnclick(View v) {
        switch (v.getId()) {
            default: break;
            case R.id.img_add_photo:
            case R.id.tv_add_photo:
            case R.id.img_add_photo_litter:
                //添加图片
                imgList.clear();
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.linear_select_type:
                //选择分类
                startActivityForResult(new Intent(mContext, FleaMarketCassifyActivity.class), TYPERESULT);
                break;
            case R.id.btn_publish:
                //发布商品
                if (isForm()) {
                    if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
                        bdLocation = Constants.bdLocation;
                    } else {
                        Constants.bdclient.start();
                        bdLocation = Constants.bdLocation;
                    }
                    goodParam.setAuthor(Integer.valueOf(Constants.userInfo.getId()));
                    goodParam.setLat(String.valueOf(bdLocation.getLatitude()));
                    goodParam.setLng(String.valueOf(bdLocation.getLongitude()));
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < imgList.size(); i++) {
                        sb.append(imgList.get(i));
                        if (i != imgList.size()-1) {
                            sb.append(",");
                        }
                    }
                    goodParam.setImg(sb.toString());
                    putFleaGoodsPersenter.putFleaGoods();
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                images.clear();
                images.addAll((ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS));
                if (images.size() > 0) {
                    hsvPhotoList.setVisibility(View.VISIBLE);
                    tvAddPhoto.setVisibility(View.GONE);
                } else {
                    hsvPhotoList.setVisibility(View.GONE);
                    tvAddPhoto.setVisibility(View.VISIBLE);
                }
                for (int i = 0; i < images.size(); i++) {
                    lubanImg(images.get(i).path);
                }
                photoAdapter = new VillagePublishHeaderPhotoAdapter(mContext, images, handler);
                recyPhotoList.setAdapter(photoAdapter);
            } else {
                Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == IntConstants.FLEARESPONSECODE) {
            id = data.getIntExtra(StringConstants.FLEATYPEID, -1);
            String name = data.getStringExtra(StringConstants.FLEATYPE);
            if (EmptyUtils.isNotEmpty(name)) {
                tvGoodType.setText(name);
            }
            if (id != -1) {
                goodParam.setCat(id);
            }
        }
    }

    /**
     * 表单验证
     */
    public boolean isForm() {
        String title = etFleaTitle.getText().toString();
        String content = etFleaContent.getText().toString();
        String price = tvGoodPrice.getText().toString();
        if (EmptyUtils.isEmpty(title)) {
            Toast.makeText(mContext, "请输入宝贝标题!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(content)) {
            Toast.makeText(mContext, "请输入宝贝描述", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (id == -1) {
            Toast.makeText(mContext, "请选择宝贝分类", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (EmptyUtils.isEmpty(price)) {
            Toast.makeText(mContext, "请输入宝贝价格", Toast.LENGTH_SHORT).show();
            return false;
        }
        goodParam.setTitle(title);
        goodParam.setPrice(price);
        goodParam.setDescrption(content);
        return true;
    }

    /**
     * 鲁班图片压缩
     *
     * @param photos
     */
    private void lubanImg(String photos) {
        Luban.with(this)
                .load(photos)
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        //  压缩成功后调用，返回压缩后的图片文件
                        param = new UpLoadPhotoParam(file);
                        uploadPhotoPersenter.uploadData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }


    @Override
    public void setData(Object o) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void message(String str) {

    }

    @Override
    public GoodsPublicParam getFleaGoodsParam() {
        return goodParam;
    }

    @Override
    public void onPutSuccesss(Object o) {
        popupWindowPublishSuccess.showAtLocation(mActivity.getCurrentFocus(), Gravity.CENTER, 0, 0);
        List<GoodIdBean> beans = (List<GoodIdBean>) o;
        if (beans.size() > 0) {
            goodsId = Integer.valueOf(beans.get(0).getId());
        }
    }

    private void initPopupSuccess() {
        popupWindowPublishSuccess = new PopupWindow(mContext);
        View popupView = LayoutInflater.from(mContext).inflate(R.layout.popup_publish_success_view, null);
        popupWindowPublishSuccess.setContentView(popupView);
        popupWindowPublishSuccess.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindowPublishSuccess.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindowPublishSuccess.setFocusable(true);
        popupWindowPublishSuccess.setBackgroundDrawable(null);
        Button btnClose = popupView.findViewById(R.id.btn_publish_success_ok);
        btnClose.setOnClickListener(v -> {
            popupWindowPublishSuccess.dismiss();
            Intent intent = new Intent(mContext, FleaMarketGoodsDetailActivity.class);
            intent.putExtra(StringConstants.FLEAGOODID, goodsId);
            startActivity(intent);
            mActivity.finish();
        });
    }

    /**
     * 监听back键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                break;
            case KeyEvent.KEYCODE_BACK:
                if (popupWindowPublishSuccess.isShowing()) {
                    return true;
                }
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public UpLoadPhotoParam uploadPhoto() {
        return param;
    }

    @Override
    public void uploadData(String urls) {
        imgList.add(urls);
    }
}
